//
//  Navigate.swift
//  MT
//
//  Created by M on 2020/1/17.
//  Copyright © 2020 张强. All rights reserved.
//

import Foundation

enum Navigate {
    /// 跳转去 safari
    case safari(url: String, params: [String: Any]? = nil)
    
}

// MARK: ------------------------------------ 跳转方法 ----------------------------------------
extension Navigate {
    
    public func push() {
        switch self {
        case let .safari(url, params):
            Navigate.to(.safari(url: url, params: params))
            break
        }
    }
    
    static func to(_ type: Navigate) {
        switch type {
        case let .safari(url, params):
            toSafari(url: url, params: params)
            break
        }
    }
    
    /// 跳转去 Safari
    private static func toSafari(url: String, params: [String: Any]?) {
        var querys: [URLQueryItem] = []
        if let params = params {
            let keys = [String](params.keys)
            for (k, _) in params.enumerated() {
                if let value: String = params[keys[k]] as? String {
                    let q = URLQueryItem(name: keys[k], value: value)
                    querys.append(q)
                }
            }
        }
        
        let urlComponents = NSURLComponents(string: url)!
        urlComponents.queryItems = querys
        if let Url = urlComponents.url {
            if UIApplication.shared.canOpenURL(Url) {
                UIApplication.shared.open(Url, options: [:]) { (flag) in
                    debugPrint("flag" , flag)
                }
            }
        }
    }
    
}
